﻿using System;
using System.Globalization;
using System.Net;
using System.Net.Cache;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Neudesic.Pulse.Converters
{
    /// <summary>
    /// Converts Uris to image source.
    /// </summary>
    public class UriToBitmapImageConverter : IValueConverter
    {
        /// <summary>
        /// Required for image downloads from the Pulse services because the service call is authenticated.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="culture">The culture.</param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter,
                              CultureInfo culture)
        {
            BitmapImage image = new BitmapImage();
            if (value != null)
            {
                try
                {
                    image.BeginInit();
                    var request = WebRequest.Create((string)value);
                    //request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
                    var credentials = new CredentialCache();
                    credentials.Add(new Uri((string)value), "NTLM", CredentialCache.DefaultNetworkCredentials);
                    request.Credentials = credentials;
                    image.StreamSource = request.GetResponse().GetResponseStream();
                    image.EndInit();
                }
                catch
                {
                    image = null;
                }
            }

            return image;
        }

        /// <summary>
        /// Converts the back.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="parameter">The parameter.</param>
        /// <param name="culture">The culture.</param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter,
                                  CultureInfo culture)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}
